package com.csi.utils;

import com.csi.domain.UserInfo;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendEmail extends Thread{

    private String from="2426994940@qq.com";       //发送者邮箱
    private String username="18622035753@163.com";       //接收者邮箱
    private String password="MGQKZRBLIOYJMEZN";       //授权码
    private String host="smtp.163.com";       //发送邮件的服务器地址

    private UserInfo userInfo;
    public SendEmail(UserInfo userInfo){
        this.userInfo=userInfo;
    }

    @Override
    public void run() {
        try {
            Properties properties = new Properties();
            properties.setProperty("mail.host", host);       //设置163邮箱服务器
            properties.setProperty("mail.transport.protocol", "smtp");       //邮件发送协议
            properties.setProperty("mail.smtp.auth", "true");       //需要验证用户名密码

            //使用JavaMail发送邮件的5个步骤
            //1.创建定义整个应用程序所需的环境信息的Session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            session.setDebug(true);       //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
            //2.通过session得到transport对象
            Transport transport = session.getTransport();
            //3.使用邮箱的用户名和授权码连上邮件服务器
            transport.connect(host, username, password);
            //4.创建邮件
            MimeMessage message = new MimeMessage(session);       //需要传递session
            message.setFrom(new InternetAddress(from));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(userInfo.getEmail()));
            message.setSubject("用户注册的邮件");       //设置邮件标题
            String info = "恭喜您注册成功，您的用户名:" + userInfo.getUserName() + "，点击链接激活:http://localhost/user/active.do?username=" + userInfo.getUserName()+ "&activecode=" + userInfo.getActiveCode();
            message.setContent(info, "text/html;charset=utf-8");
            message.saveChanges();       //保存修改
            //5.发送邮件
            transport.sendMessage(message, message.getAllRecipients());
            //6.关闭连接
            transport.close();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}
